<?php

class sfAssetToolkit{
    public static function _create_cropped_image($from_img_path , $new_image_name , $targ_w , $targ_h , $x=0 , $y=0, $from_w=100, $from_h=100){

        $thumb_dir = self::_get_thumb_dir();

        if(!is_dir($thumb_dir)){
            mkdir( $thumb_dir );
            chmod( $thumb_dir , 0777);
        }

        $to_image_path	= $thumb_dir."/{$targ_w}x{$targ_h}";
        if(!is_dir($to_image_path)){
            mkdir($to_image_path);
            chmod($to_image_path, 0777);
        }

        $jpeg_quality = 90;

        $img_r = imagecreatefromjpeg($from_img_path);

        if(!$img_r){
            $img_r = imagecreatefrompng($from_img_path);
        }
        if(!$img_r){
            $img_r = imagecreatefromgif($from_img_path);
        }

        if(!$img_r){
            return false;
        }
        $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

        imagecopyresampled( $dst_r,$img_r,0,0,$x,$y,
        $targ_w,$targ_h,$from_w,$from_h);

        imagejpeg($dst_r,$to_image_path.'/'.$new_image_name ,$jpeg_quality);

        return self::_get_thumb_dir(false).'/'.$new_image_name;

    }


    #### from globals
    public static function _get_thumb_dir($physical_path=true){
        sfContext::getInstance()->getConfiguration()->loadHelpers('Asset');
        if($physical_path){
            return sfConfig::get('sf_web_dir').'/'.sfConfig::get('app_sfAssetsLibrary_thumb_dir');
        }else{
            return trim(image_path('/'.sfConfig::get('app_sfAssetsLibrary_thumb_dir')),'.png');
        }
    }

    public static function _get_thumbs_dims(){
        //var_dump(sfConfig::get('sfAssetsLibrary_app_thumbs_dim'));exit;
        return sfConfig::get('app_sfAssetsLibrary_thumbs_dim'
        ,array(
        'Small'=>array('w'=>'80','h'=>'60')
        , 'Meduim'=>array('w'=>'200','h'=>'150')
        , 'Large'=>array('w'=>'500','h'=>'400')
        ) );

    }

    public static function _to_web_image_path($path){
        sfContext::getInstance()->getConfiguration()->loadHelpers('Asset');
        return image_path(str_replace(array(sfConfig::get('sf_web_dir'),'\\'),array('','/'),$path));
    }



}